package com.swust.excel.support;

import com.alibaba.fastjson2.JSON;
import com.swust.excel.entity.LogInfo;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author: Chen Yixing
 * @since: 2023/11/17 10:49:31
 * @description:
 */
@Component
public class DataSourceSupport {
    /**
     * 设置返回的文件名，以及返回的文件后缀
     */
    public void initExcelResponse(HttpServletResponse response, String fileName) throws Exception {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

    /**
     * 设置ZIP返回的文件名，以及返回的文件后缀
     */
    public void initZipExcelResponse(HttpServletResponse response, String fileName) {
        response.setContentType("application/x-zip-compressed");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".zip");
    }

    /**
     * 设置失败时候的返回信息
     */
    public void initFailResponse(HttpServletResponse response) throws Exception {
        // 重置response
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        Map<String, String> map = new HashMap<>();
        map.put("status", "failure");
        map.put("message", "没有日志记录！");
        response.getWriter().println(JSON.toJSONString(map));
    }

    public List<LogInfo> initLogInfo() {
        List<LogInfo> logInfos = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            logInfos.add(new LogInfo("" + i, UUID.randomUUID().toString()));
        }
        return logInfos;
    }
}
